package com.xiaoyun.alllearning.controller;

import com.xiaoyun.alllearning.domain.common.ResponseResult;
import com.xiaoyun.alllearning.exception.BusinessException;
import com.xiaoyun.alllearning.exception.ErrorCodeEnum;
import com.xiaoyun.alllearning.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.io.IOException;

@RestController
@RequestMapping("/api/files")
@Slf4j
@Api
public class FileController {

    @Resource(name = "localFileServiceImpl")
    private FileService fileService;

    @ApiOperation("upload")
    @PostMapping
    private ResponseResult<String> upload(@NotNull MultipartFile file) {

        try {
            fileService.upload(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            log.error("文件上传失败:{}", e);
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, e);
        }

        return ResponseResult.success(file.getOriginalFilename());
    }


}
